package com.javaweb.bookstore.controller;

import com.javaweb.bookstore.component.FileRepository;
import com.javaweb.bookstore.component.IBookManager;
import com.javaweb.bookstore.component.JdbcBookManager;
import com.javaweb.bookstore.entity.Book;
import com.javaweb.bookstore.entity.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("book")
public class BookController {
    @Autowired ApplicationContext context;
    @Autowired IBookManager manager;//服务的消费者

    @Autowired
    FileRepository fireRep;




    @PostMapping ("create")
    public ResponseEntity create(@RequestParam("image") MultipartFile file, Book book) throws IOException {
        String  id = UUID.randomUUID().toString();
        String image = fireRep.storeFile(file, id);
        book.setImageUrl(image);


        JdbcBookManager bean = context.getBean(JdbcBookManager.class);
        Map<String, IBookManager> bs = context.getBeansOfType(IBookManager.class);

        manager.createBook(book);


        ResponseEntity re = new ResponseEntity(true, "create success!", null);
        return re;
    }
    @GetMapping("search")
    public ResponseEntity search(String keyword){

        List<Book> data = manager.getBooks(keyword);
        ResponseEntity re = new ResponseEntity(true, "remove success!", data);
        return re;
    }

    @PostMapping("upload")
    public ResponseEntity upload(@RequestParam("file") MultipartFile file){
        return new ResponseEntity(true, "", null);

    }
    @GetMapping("image")
    public void bookImage(String id, HttpServletResponse resp) throws IOException {
        Book b = manager.getBook(id);
        String fname = b.getImageUrl();
        ServletOutputStream out = resp.getOutputStream();
        fireRep.stream(out,fname);

    }



}
